﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using ZuesControls.Helpers;

namespace ZuesControls.Behaviors
{
    public class InlineEditBehavior : Behavior<Border>
    {
        private TextBlock _textBlock;
        private TextBox _textBox;
        public InlineEditBehavior() { }
        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.PreviewMouseLeftButtonDown += OnMouseClick;
            AssociatedObject.KeyDown += OnKeyDown;

            // 找到子元素
            _textBlock = VisualHelper.FindChild<TextBlock>(AssociatedObject, "PART_TextBlock");
            _textBox = VisualHelper.FindChild<TextBox>(AssociatedObject, "PART_TextBox");
        }

        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (_textBox == null || _textBlock == null) return;
            if (_textBox.Visibility == Visibility.Visible)
            {
                if (e.Key == Key.Enter)
                {
                    // 提交修改
                    _textBox.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();
                    ExitEditMode();
                    e.Handled = true;
                }
                else if (e.Key == Key.Escape)
                {
                    // 放弃修改
                    _textBox.GetBindingExpression(TextBox.TextProperty)?.UpdateTarget();
                    ExitEditMode();
                    e.Handled = true;
                }
            }
        }

        private void OnMouseClick(object sender, MouseButtonEventArgs e)
        {
            if (_textBlock == null || _textBox == null) return;
            if (e.ClickCount == 2)
            {
                _textBlock.Visibility = Visibility.Hidden;
                _textBox.Visibility = Visibility.Visible;
                _textBox.Focus();
                _textBox.SelectAll();
            }

        }
        private void ExitEditMode()
        {
            _textBox.Visibility = Visibility.Hidden;
            _textBlock.Visibility = Visibility.Visible;
            _textBlock.Focus();
        }
    }
}
